// API配置文件 - 定义所有后端接口路径
const API_CONFIG = {
    // 基础URL
    BASE_URL: '',
    
    // 认证相关接口
    AUTH: {
        LOGIN: '/api/auth/login',
        REGISTER: '/api/auth/register',
        LOGOUT: '/api/auth/logout',
        REFRESH_TOKEN: '/api/auth/refresh-token',
        FORGOT_PASSWORD: '/api/auth/forgot-password',
        RESET_PASSWORD: '/api/auth/reset-password'
    },
    
    // 用户相关接口
    USER: {
        PROFILE: '/user/profile',
        UPDATE_PROFILE: '/user/profile',
        CHANGE_PASSWORD: '/user/change-password'
    },
    
    // 问诊相关接口
    CONSULTATION: {
        CREATE: '/consultations',
        LIST: '/consultations',
        DETAIL: '/consultations/{id}',
        MESSAGES: '/consultations/{id}/messages',
        SEND_MESSAGE: '/consultations/{id}/messages'
    },
    
    // 管理员相关接口
    ADMIN: {
        // 用户管理
        USERS: '/admin/users',
        USER_DETAIL: '/admin/users/{id}',
        UPDATE_USER: '/admin/users/{id}',
        DELETE_USER: '/admin/users/{id}',
        
        // 供应商管理
        SUPPLIERS: '/admin/suppliers',
        SUPPLIER_DETAIL: '/admin/suppliers/{id}',
        CREATE_SUPPLIER: '/admin/suppliers',
        UPDATE_SUPPLIER: '/admin/suppliers/{id}',
        DELETE_SUPPLIER: '/admin/suppliers/{id}',
        
        // 角色管理
        ROLES: '/admin/roles',
        ROLE_DETAIL: '/admin/roles/{id}',
        CREATE_ROLE: '/admin/roles',
        UPDATE_ROLE: '/admin/roles/{id}',
        DELETE_ROLE: '/admin/roles/{id}',
        
        // 问诊记录管理
        ALL_CONSULTATIONS: '/admin/consultations',
        CONSULTATION_MESSAGES: '/admin/consultations/{id}/messages'
    },
    
    // 工具函数：获取完整URL
    getFullUrl: function(endpoint, params = {}) {
        let url = this.BASE_URL + endpoint;
        
        // 替换URL中的参数占位符
        Object.keys(params).forEach(key => {
            const placeholder = `{${key}}`;
            if (url.includes(placeholder)) {
                url = url.replace(placeholder, params[key]);
            }
        });
        
        return url;
    },
    
    // 发起请求的辅助函数
    request: async function(endpoint, options = {}) {
        const url = this.getFullUrl(endpoint, options.params);
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'include' // 包含cookies
        };
        
        // 如果有token，添加到请求头
        const token = localStorage.getItem('access_token');
        if (token) {
            defaultOptions.headers['Authorization'] = `Bearer ${token}`;
        }
        
        // 合并选项，确保headers正确合并
        const mergedOptions = {
            ...defaultOptions,
            ...options,
            headers: {
                ...defaultOptions.headers,
                ...options.headers
            }
        };
        
        try {
            const response = await fetch(url, mergedOptions);
            
            // 检查是否需要刷新token
            const newToken = response.headers.get('X-Refresh-Token');
            if (newToken) {
                localStorage.setItem('access_token', newToken);
            }
            
            // 处理可能的非JSON响应
            let data;
            try {
                data = await response.json();
            } catch (e) {
                data = { message: '响应格式错误' };
            }
            
            if (!response.ok) {
                throw new Error(data.message || `HTTP error! status: ${response.status}`);
            }
            
            return data;
        } catch (error) {
            console.error('API request failed:', error);
            throw error;
        }
    },
    
    // 刷新token方法
    refreshToken: async function() {
        try {
            // 使用request方法统一处理请求
            const data = await this.request(this.AUTH.REFRESH_TOKEN, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });
            
            if (data && data.data && data.data.access_token) {
                localStorage.setItem('access_token', data.data.access_token);
                return data.data.access_token;
            }
            
            // 如果刷新失败，清除token并跳转到登录页
            localStorage.removeItem('access_token');
            window.location.href = '/auth/login';
            return null;
        } catch (error) {
            console.error('刷新token失败:', error);
            localStorage.removeItem('access_token');
            window.location.href = '/auth/login';
            return null;
        }
    }
};

// 导出配置（支持CommonJS和全局变量两种方式）
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = API_CONFIG;
} else {
    window.API_CONFIG = API_CONFIG;
}